package com.cxz.study.infra.outbound.inventory;

import com.cxz.study.domain.order.service.InventoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @className: InventoryServiceImpl
 * @author: ocxz1
 * @date: 2025/6/15 上午11:18
 * @Version: 1.0
 * @description: ddd-struct3
 */
@RequiredArgsConstructor
@Service
public class InventoryServiceImpl implements InventoryService {

    private final StringRedisTemplate redisTemplate;

    @Override
    public boolean isEnough(Long productId, int count) {

        String stockStr = redisTemplate.opsForValue().get("product:" + productId + ":count");
        int stock = stockStr == null || stockStr.isEmpty() ? 0 : Integer.parseInt(stockStr);
        return stock >= count;
    }

    @Override
    public void deduct(Long productId, int count) {
        redisTemplate.opsForValue().decrement("product:" + productId + ":count", count);
    }

    @Override
    public void cancelDeduct(Long productId, int count) {
        redisTemplate.opsForValue().increment("product:" + productId + ":count", count);
    }
}
